<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
    >
      <el-form-item label="群组名称">
        <el-input
          v-model="queryParams.groupName"
          placeholder="群组名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          v-hasPermi="['system:group:query']"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >{{ $t("common.csearch") }}</el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.creset') }}</el-button> -->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:group:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{ $t("common.caddkey") }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:role:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >{{ $t('common.cupdate') }}</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:role:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >{{ $t("common.cdelete") }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:role:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >{{ $t("common.cexport") }}</el-button
        >
      </el-col> -->
      <!-- <right-toolbar :show-search.sync="showSearch" @queryTable="getList" /> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" type="index" :index="0" />
      <el-table-column label="群名" prop="groupName" width="150" />
      <el-table-column label="人员" prop="memberIds" />

      <el-table-column
        :label="$t('common.coperation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:group:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >{{ $t("common.cupdate") }}</el-button>

          <el-button
            v-hasPermi="['system:group:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >{{ $t("common.cdelete") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--
    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="16">
          <el-form-item label="群组名称">
            <el-input v-model="form.groupName" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="人员">
            <el-select v-model="value1" multiple placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button
            type="primary"
            style="margin-left: 20px"
            @click="submitForm"
          >
            添加
          </el-button>
        </el-col>
      </el-form>

      <el-table :data="list">
        <el-table-column label="序号" type="index" :index="0" />
        <el-table-column label="姓名" prop="userName" />
        <el-table-column label="手机号" prop="phonenumber" />
        <el-table-column label="邮箱地址" prop="email" />

        <el-table-column
          :label="$t('common.coperation')"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button

              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="groudelete(scope.row)"
            >{{ $t("common.cdelete") }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import i18n from '@/utils/lang/index'
import {
  listGroup,
  getGroup,
  delGroup,
  addGroup,
  removeGroup,
  updateGroup,
  dataScope,
  changeGroupStatus
} from '@/api/system/group'
import { listUser } from '@/api/system/user'

export default {
  name: 'Group',
  data() {
    return {
      roleIds: '',
      list: [],
      value1: null,
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: undefined

      },
      queryParam1: {
        pageNum: 1,
        pageSize: 1000
      },
      // 表单参数
      form: {
        groupId: undefined,
        groupName: undefined,
        memberIds: ''
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '群组名称不能为空', trigger: 'blur' }
        ],
        roleKey: [{ required: true, message: '人员不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    userlist() {
      listUser(this.addDateRange(this.queryParam1)).then((response) => {
        this.options = response.rows
      })
    },

    /** 查询角色列表 */
    getList() {
      this.loading = true
      let arrs = []
      listGroup(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.roleList = response.data

          //   this.total = response.total;
          if (this.roleList) {
            this.roleList.forEach((element) => {
              arrs = []
              if (element.members) {
                element.members.forEach((a) => {
                  arrs.push(a.userName)
                })

                element.memberIds = arrs.toString()
              }
            })
            this.loading = false
          }
        }
      )
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data
      })
    },
    /** 查询部门树结构 */
    getDeptTreeselect() {
      deptTreeselect().then((response) => {
        this.deptOptions = response.data
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        groupId: '',
        groupName: undefined,
        memberIds: ''
      }
      this.value1 = null
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.list = []
      this.open = true
      this.userlist()
      this.title = '新增'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.list = []
      this.reset()

      this.roleIds = row.groupId
      this.value1 = []
      this.userlist()
      getGroup(this.roleIds).then((response) => {
        this.form = {
          groupId: response.data.groupId,
          groupName: response.data.groupName,
          memberIds: ''
        }
        this.list = response.data.members
        this.open = true
      })
    },

    /** 提交按钮 */
    submitForm: function() {
      console.log(this.value1)
      if (this.value1) {
        this.form.memberIds = this.value1.toString()
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          addGroup(this.form).then((response) => {
            this.msgSuccess('操作成功')
            //   this.open = false;
            getGroup(response.data.groupId).then((response) => {
              this.form = {
                groupId: response.data.groupId,
                groupName: response.data.groupName,
                memberIds: ''
              }
              this.roleIds = response.data.groupId
              this.list = response.data.members
            })
            this.getList()
          })
        }
      })
    },
    groudelete(row) {
      const datas = {
        groupId: this.roleIds,
        memberIds: row.userId
      }
      this.$confirm('是否确认删除数据项?', this.$i18n.t('menuManage.title'), {
        confirmButtonText: i18n.t('common.cok'),
        cancelButtonText: this.$i18n.t('operating.cancel'),
        type: 'warning'
      })
        .then(() => {
          removeGroup(datas).then((response) => {
            this.msgSuccess('删除成功')
            getGroup(this.roleIds).then((response) => {
              this.form = {
                groupId: response.data.groupId,
                groupName: response.data.groupName,
                memberIds: ''
              }
              this.roleIds = response.data.groupId
              this.list = response.data.members
            })
          })
        })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
     console.log(row)
      let roleId = row.groupId || this.ids
      this.$confirm('是否确认删除数据项?', this.$i18n.t('menuManage.title'), {
        confirmButtonText: i18n.t('common.cok'),
        cancelButtonText: this.$i18n.t('operating.cancel'),
        type: 'warning'
      })
        .then(function() {
          return delGroup( roleId)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/role/export',
        {
          ...this.queryParams
        },
        `role_${new Date().getTime()}.xls`
      )
    },
    /** 导出按钮操作 */
    handleExport11() {
      this.queryParams = {}
      this.download(
        'system/role/export',
        {
          ...this.queryParams
        },
        `role_${new Date().getTime()}.xls`
      )
    }
  }
}
</script>
